import sys
import json
from Crypto.Cipher import AES
from Crypto.Util.Padding import unpad
from base64 import b64decode


def decrypt_with_aes(encrypted_message, aes_key):
    try:
        # 如果 aes_key 为空或仅包含空格，使用默认密钥
        if not aes_key.strip():
            aes_key = '63474e6489b45592'
        key_bytes = aes_key.encode('utf-8')
        iv = "1234567890123456".encode('utf-8')
        cipher = AES.new(key_bytes, AES.MODE_CBC, iv)
        encrypted_data_bytes = b64decode(encrypted_message)
        decrypted_data = cipher.decrypt(encrypted_data_bytes)
        unpad_data = unpad(decrypted_data, AES.block_size)
        decrypted_string = unpad_data.decode('utf-8')
        return decrypted_string
    except ValueError as e:
        print("参数不对", e)
        sys.exit(1)
    except Exception as e:
        print("Error发生:", e)
        sys.exit(1)


def read_encrypted_message_from_file(file_path):
    try:
        with open(file_path, 'r') as file:
            encrypted_message = file.read().strip()
            return encrypted_message
    except FileNotFoundError:
        print("Error: 文件不存在")
        sys.exit(1)
    except IOError as e:
        print(f"一个 I/O Error 发生: {e.strerror}")
        sys.exit(1)


def write_output_to_file(output_path, data):
    try:
        with open(output_path, 'w', encoding='utf-8') as file:
            try:
                # 尝试将字符串解析为JSON，然后美化输出
                parsed_data = json.loads(data)
                json.dump(parsed_data, file, ensure_ascii=False, indent=4)
            except ValueError:
                # 如果不是JSON，直接写入
                file.write(data)
    except IOError as e:
        print(f"写入文件时出现 I/O Error: {e.strerror}")
        sys.exit(1)


file_path = '../data/encrypted_message.txt'
output_path = '../filesOutput/decrypted_message.txt'  # 输出文件的路径

encrypted_message = read_encrypted_message_from_file(file_path)
aes_key = 'e6d3d73a2da4e440'  # 如果 aes_key 为空，则使用默认密钥 '63474e6489b45592'

decrypted_message = decrypt_with_aes(encrypted_message, aes_key)
print("解密后的字符串:", decrypted_message)

write_output_to_file(output_path, decrypted_message)